from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from myadmin import models

# 购物车列表
def cart_list(request):
    return render(request,'home/cart/cart.html')

# 商品加入购物车
def cart_add(request):
    # 接收 ajax 传来的 信息  商品 id 购买数量
    gid = request.GET['gid']
    num = int(request.GET['num'])

    #  获取商品对象
    ob = models.Goods.objects.get(id = gid)
    # 准备商品数据
    goods = {'gid':ob.id,'gname':ob.title,'gprice':ob.price,'gpic':ob.pic,'gnum':num}

    # 获取购物车数据
    """
    {
        'pid':{商品数据},
        'pid2':{商品数据}
    }
    
    """
    data = request.session.get('Cart',{})
    # 判断 购物车是否已经存在 该商品
    if gid in data:
        # 商品的数量相加
        data[gid]['gnum'] += int(num)
    else:
        # 存入session
        data[gid] = goods
    # 将商品重新存入session
    request.session['Cart'] = data
    return JsonResponse({'error':0,'msg':'加入购物车失败'})

# 修改数量

def cart_edit(request):
    # 获取传过来的 商品 和数量
    gid = request.GET.get('gid')
    num = int(request.GET.get('num'))
    # 获取购物车对象
    data = request.session['Cart']
    # 修改对应商品的 gnum(商品数量) 值
    data[gid]['gnum'] = num
    # 将购物车重新存入session
    request.session['Cart'] = data
    return HttpResponse('<script>location.href="'+reverse('home_cart_list')+'"</script>')

# 删除商品
def cart_del(request,gid):
    # 获取session 购物车
    data = request.session.get('Cart',None)
    # 删除对应的商品
    del data[gid]
    # 将购物车重新存入session
    request.session['Cart'] = data
    return HttpResponse('<script>location.href="' + reverse('home_cart_list') + '"</script>')

# 清空购物车
def cart_clear(request):
    request.session['Cart'] = {}
    return HttpResponse('<script>location.href="' + reverse('home_cart_list') + '"</script>')